package main
 
import (
   "bytes"
   "context"
   "fmt"
   "github.com/elastic/go-elasticsearch/v7"
   "github.com/elastic/go-elasticsearch/v7/esapi"
   "k8s.io/api/events/v1beta1"
   "k8s.io/apimachinery/pkg/runtime"
   "k8s.io/apimachinery/pkg/util/json"
   "k8s.io/client-go/informers"
   "k8s.io/client-go/kubernetes"
   "k8s.io/client-go/tools/cache"
   "k8s.io/client-go/tools/clientcmd"
   "math/rand"
   "strconv"
   "time"
)
 
func mustSuccess(err error) {
   if err != nil {
      panic(err)
   }
}
 
func main() {
   rand.Seed(time.Now().UnixNano())
   config, err := clientcmd.BuildConfigFromFlags("", "/Users/qiulingwei/Projects/kube-goclient/kubeconfig")
   mustSuccess(err)
 
   clientset, err := kubernetes.NewForConfig(config)
   mustSuccess(err)
   sharedInformers := informers.NewSharedInformerFactory(clientset, 0)
   stopChan := make(chan struct{})
   defer close(stopChan)
 
   eventInformer := sharedInformers.Events().V1beta1().Events().Informer()
   addChan := make(chan v1beta1.Event)
   deleteChan := make(chan v1beta1.Event)
   eventInformer.AddEventHandlerWithResyncPeriod(cache.ResourceEventHandlerFuncs{
      AddFunc: func(obj interface{}) {
         unstructObj, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj)
         mustSuccess(err)
         event := &v1beta1.Event{}
         err = runtime.DefaultUnstructuredConverter.FromUnstructured(unstructObj, event)
         mustSuccess(err)
         addChan <- *event
      },
      UpdateFunc: func(oldObj, newObj interface{}) {
      },
      DeleteFunc: func(obj interface{}) {
      },
   }, 0)
 
   go func() {
      for  {
         select {
         case event := <- addChan:
            str, err := json.Marshal(&event)
            mustSuccess(err)
	    fmt.Println(string(str))
            //esinsert(str)
            break
         case <-deleteChan:
            break
         }
      }
   }()
   eventInformer.Run(stopChan)
}
 
func esinsert(str []byte){
   cfg := elasticsearch.Config{
      Addresses: []string{
         "xxxxxx",
         "xxxxx",
         "xxxxx",
      },
      Username: "xxx",
      Password: "xxxxxx",
   }
   es, _ := elasticsearch.NewClient(cfg)
   req := esapi.CreateRequest{
      Index:        "qlw-index",
      DocumentType: "_doc",
      DocumentID:   strconv.FormatInt(time.Now().Unix(),10) + strconv.Itoa(rand.Int()),
      Body:         bytes.NewReader(str),
   }
   res, err := req.Do(context.Background(), es)
   defer res.Body.Close()
   if err!=nil  {
      fmt.Println(res.String())
   }
}


